package fv;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.sql.*;

/**
 * Servlet implementation class comments
 */
public class comments extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	public JSONObject json = new JSONObject();
	JSONArray jsonArr = new JSONArray();
	int retcnt = 25;
	String outfitid = null;
	String sqlstr = null;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public comments() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		outfitid = request.getParameter("id");
		sqlstr = "select * from comments where photoid = " + outfitid + " order by commid desc limit " + retcnt;
				
		Connection conn = mysqlconn.getConn();
		json.clear();
		try {
			Statement s = conn.createStatement();
			s.executeQuery(sqlstr);
			ResultSet rs = s.getResultSet();
			
			while (rs.next())
			{
				json.put("comment", rs.getString(3));
				jsonArr.add(json);
			}
			
			rs.close();
			s.close();
		}
		catch(Exception e)
		{
			System.out.println(e.getMessage());
		}
		mysqlconn.closeConn(conn);
		response.setContentType("application/json");
		response.getWriter().write(jsonArr.toString());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String comments = request.getParameter("comment");
		outfitid = request.getParameter("id");
		sqlstr = "insert into comments(photoid, content) values(" + outfitid + ", '" + comments + "')";
		Connection conn = mysqlconn.getConn();
		if (conn != null) {
			try {
				Statement s = conn.createStatement();
				s.execute(sqlstr);
				s.close();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		mysqlconn.closeConn(conn);
	}

}
